package com.punai.standard.service.impl;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.map.multi.ListValueMap;
import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.github.pagehelper.PageInfo;
import com.punai.common.core.domain.TreeBo;
import com.punai.common.core.domain.entity.SysDictData;
import com.punai.common.core.page.TableDataInfo;
import com.punai.common.exception.ServiceException;
import com.punai.common.utils.DictUtils;
import com.punai.common.utils.PageUtils;
import com.punai.common.utils.ParseContentUtil;
import com.punai.standard.domain.*;
import com.punai.standard.domain.bo.CJCategoryFbBo;
import com.punai.standard.domain.constants.StaConstants;
import com.punai.standard.domain.vo.StaFeeVo;
import com.punai.standard.mapper.*;
import com.punai.standard.service.IStaFbChapterService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.*;
import java.util.function.Function;
import java.util.stream.Collectors;

/**
 * 分包费用项章节Service业务层处理
 *
 * @author zxw
 * @date 2022-12-13
 */
@Service
public class StaFbChapterServiceImpl extends ServiceImpl<StaFbChapterMapper, StaFbChapter> implements IStaFbChapterService {
    @Autowired
    private StaFbChapterMapper staFbChapterMapper;
    @Autowired
    private StaFbFeeMapper staFbFeeMapper;
    @Autowired
    private StaGxFeeMapper staGxFeeMapper;
    @Autowired
    private StaLinkFeatureMapper staLinkFeatureMapper;
    @Autowired
    private StaLinkGxfeeCategoryMapper staLinkGxfeeCategoryMapper;
    @Autowired
    private StaLinkFbGxMapper staLinkFbGxMapper;
    @Autowired
    private StaSubpkLinkConsumeMapper consumeMapper;
    @Autowired
    private StaVersionMapper staVersionMapper;

    @Override
    public List<TreeBo> treeData(String versionId, Long companyId) {
        List<StaFbChapter> staFbChapters = staFbChapterMapper.selectList(
                Wrappers.<StaFbChapter>lambdaQuery()
                        .eq(StaFbChapter::getVersionId, versionId)
        );

        List<TreeBo> result = new ArrayList<>();
        if (CollUtil.isEmpty(staFbChapters)) {
            return result;
        }
        result = TreeBo.convert(staFbChapters).get(0).getChildren();
        return result;
    }

    private void setGxFbType(List<TreeBo> treeBos, String type) {
        if (CollUtil.isNotEmpty(treeBos)) {
            for (TreeBo treeBo : treeBos) {
                treeBo.setGxFbType(type);
                setGxFbType(treeBo.getChildren(), type);
            }
        }
    }


    @Override
    public TableDataInfo feeList(StaFeeVo vo, Long companyId) {

        String chapterId = vo.getChapterId();
        String versionId = vo.getVersionId();
        List<String> chapterIds = staFbChapterMapper.selectChildrenIdById(chapterId, versionId);
        chapterIds.add(0,chapterId);

        PageUtils.startPage();
        List<StaFbFee> staFbFees = staFbFeeMapper.selectStaGxFeeList(vo,versionId,chapterIds);
        if (CollUtil.isEmpty(staFbFees)) {
            return new TableDataInfo(staFbFees, 0);
        }
        Long total = new PageInfo(staFbFees).getTotal();
        List<String> fbIds = staFbFees.stream().map(StaFbFee::getId).collect(Collectors.toList());

        // 特征现在只关联 标准费用项
        // 需要查找 gxId
        List<StaLinkFbGx> staLinkFbGxes = staLinkFbGxMapper.selectList(
                Wrappers.<StaLinkFbGx>lambdaQuery()
                        .select(StaLinkFbGx::getGxId, StaLinkFbGx::getFbId)
                        .eq(StaLinkFbGx::getVersionId, versionId)
                        .in(StaLinkFbGx::getFbId, fbIds)
                        .orderByAsc(StaLinkFbGx::getSort)
        );


        LambdaQueryWrapper<StaVersion> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(StaVersion::getCompanyId, companyId);
        wrapper.eq(StaVersion::getType, StaConstants.GX_TYPE);
        wrapper.eq(StaVersion::getSpecId, vo.getChapterType());
        wrapper.orderByDesc(StaVersion::getCreateTime);
        wrapper.last("limit 1");
        StaVersion staVersion = staVersionMapper.selectOne(wrapper);
        if (staVersion == null) {
            throw new ServiceException("千年难遇的BUG，请联系管理员");
        }
        versionId = staVersion.getId();

        ListValueMap<String, String> fbGxIdMap = new ListValueMap<>();
        if (CollUtil.isNotEmpty(staLinkFbGxes)) {
            for (StaLinkFbGx staLinkFbGx : staLinkFbGxes) {
                fbGxIdMap.putValue(staLinkFbGx.getFbId(), staLinkFbGx.getGxId());
            }
        }

        // 包含内容,工作内容
        if (CollUtil.isNotEmpty(staLinkFbGxes)) {
            for (StaFbFee staFbFee : staFbFees) {
                List<String> gxIds = fbGxIdMap.get(staFbFee.getId());
                List<StaGxFee> staGxFees = staGxFeeMapper.selectList(
                        Wrappers.<StaGxFee>lambdaQuery()
                                .in(StaGxFee::getId, gxIds)
                                .eq(StaGxFee::getVersionId, staVersion.getId()).orderBy(true, true, StaGxFee::getOrderNum)
                );
                Map<String, StaGxFee> staGxFeesMap = staGxFees.stream().collect(Collectors.toMap(StaGxFee::getId, Function.identity()));

                Map<String, List<String>> fbContent = ParseContentUtil.getContentObj();


                List<String> subRange = new ArrayList<>();
                for (String gxId : gxIds) {
                    StaGxFee staGxFee = staGxFeesMap.get(gxId);
                    subRange.add(staGxFee.getSuitableRange());
                    ParseContentUtil.mergeContent(fbContent, staGxFee.getContent());
                }

                //补充工作内容
                ParseContentUtil.mergeContent(fbContent, staFbFee.getContent());
                staFbFee.setContent(ParseContentUtil.parseContent(fbContent));
                staFbFee.setSuitableRange(StrUtil.join("；", subRange) + "；");

                // 关联特征
                staFbFee.setFeatureValues(StrUtil.emptyToDefault(staLinkFeatureMapper.selectFeatureBoFb(gxIds, versionId, companyId),""));

                // 关联类别
                List<CJCategoryFbBo> cjCategoryFbBos = staLinkGxfeeCategoryMapper.selectCategoryFbBo(gxIds, versionId, companyId);
                if (CollUtil.isNotEmpty(cjCategoryFbBos)) {
                    // 去重
                    /// 以后用的时候再调吧
                    ArrayList<CJCategoryFbBo> CJCategoryFbBoList = cjCategoryFbBos.stream().collect(Collectors.collectingAndThen(
                            Collectors.toCollection(() -> new TreeSet<>(Comparator.comparing(CJCategoryFbBo::getId))), ArrayList::new));
                    staFbFee.setCjCategoryFbBos(CJCategoryFbBoList);
                }

                gxIds.clear();
                subRange.clear();
                staGxFees.clear();
                fbContent.clear();
                staGxFeesMap.clear();
                cjCategoryFbBos.clear();
            }
        }
        return new TableDataInfo(staFbFees, total.intValue());
    }

    @Override
    public List<String> getSpecialtyList(Long companyId) {
        List<String> versionSpecialty = new ArrayList<>();

        List<String> specIds = staVersionMapper.selectSpecByType(companyId, StaConstants.FB_TYPE);
        if (CollUtil.isNotEmpty(specIds)) {
            List<SysDictData> fee_projecttype = DictUtils.getDictCache("fee_projecttype");
            for (SysDictData sysDictData : fee_projecttype) {
                if (specIds.contains(sysDictData.getDictValue())) {
                    versionSpecialty.add(sysDictData.getDictValue());
                }
            }
        }
        return versionSpecialty;
    }

    @Override
    public List<StaVersion> getVersionListBySpecId(Long companyId, String topId) {
        return staVersionMapper.selectListBySpecId(companyId,StaConstants.FB_TYPE, topId.trim());
    }

}
